import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:management/app/cons.dart';
import 'package:management/views/pages/ask_for_leave_page.dart';
import 'package:management/views/pages/monitor_page.dart';
import '../pages/gate_page.dart';
import '../pages/mine_page.dart';
import '../pages/visitor_page.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var _position = 0; //当前激活页
  final _ctl = PageController(); //控制器
  final _colors = [
    Colors.blue,
    Colors.green,
    Colors.yellow,
    Colors.blue,
    Colors.purple
  ];
  DateTime? lastPopTime;

  BottomNavigationBarType _type = BottomNavigationBarType.fixed;

  bool get isShifting => _type == BottomNavigationBarType.shifting;

  @override
  void initState() {
    SystemChrome.setEnabledSystemUIOverlays([]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // DeviceHelper.getDeviceScreenInfo(context);
    // DeviceHelper.getDeviceInfo();
    return WillPopScope(
      child: Scaffold(
        body: PageView(
          controller: _ctl,
          children: _buildPageContent(),
          onPageChanged: (position) {
            setState(() => _position = position);
          },
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _position,
          elevation: 8.0,
          type: _type,
          iconSize: 45,
          fixedColor: isShifting ? Colors.white : _colors[_position],
          selectedLabelStyle: TextStyle(fontWeight: FontWeight.bold),
          showSelectedLabels: true,
          showUnselectedLabels: false,
          items: _buildBottomItems(),
          onTap: (position) {
            _ctl.jumpToPage(position);
            setState(() {
              _position = position;
            });
          },
        ),
      ),
      onWillPop: () async {
        //点击返回键的操作
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime!) > Duration(seconds: 2)) {
          lastPopTime = DateTime.now();
          Fluttertoast.showToast(msg: "再按一次退出");
          return false;
        }
        lastPopTime = DateTime.now();
        return true;
      },
    );
  }

  //主体内容列表
  List<Widget> _buildPageContent() =>
      <Widget>[
        VisitorRegistration(),
        AskForLeave(),
        GatePage(),
        MonitorPage(),
        // FacePage(),
        MinePage()
      ];

  //生成底部导航栏Item
  List<BottomNavigationBarItem> _buildBottomItems() => Cons.bottomNavMap.keys
      .map(
        (e) => BottomNavigationBarItem(
            icon: Icon(Cons.bottomNavMap[e]),
            label: e,
            backgroundColor: _colors[_position]),
      ).toList();

  @override
  void dispose() {
    _ctl.dispose();
    super.dispose();
  }
}
